package com.example.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.reggie.domain.Dish;
import com.example.reggie.domain.DishFlavor;
import com.example.reggie.dto.DishDto;
import com.example.reggie.service.DishFlavorService;
import com.example.reggie.service.DishService;
import com.example.reggie.mapper.DishMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author 27935
* @description 针对表【dish(菜品管理)】的数据库操作Service实现
* @createDate 2024-08-03 12:00:49
*/
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
    implements DishService{

    @Autowired
    DishFlavorService dishFlavorService;
    @Override
    public void dishAdd(DishDto dishDto) {
        // 往菜品表中添加菜品
        this.save(dishDto);
        Long dishId = dishDto.getId();
        // 往口味表中添加口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        // 循环修改每个口味数据中的dishId
        for(int i=0;i<flavors.size();i++){
            flavors.get(i).setDishId(dishId);
        }
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public void dishUpdate(DishDto dishDto) {
        this.updateById(dishDto);
        //清理当前菜品对应口味数据---dish_flavor表的delete操作
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());

        dishFlavorService.remove(queryWrapper);

        //添加当前提交过来的口味数据---dish_flavor表的insert操作
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
    }
}




